package com.logistics.utils.security;

import org.apache.tomcat.util.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class EncryptionUtils {

    private static final String ALGORITHM = "AES";

    private static final String ENCODING = "UTF-8";

    /**
     * BASE64加密
     * @param plainText
     * @param key
     * @return
     * @throws Exception
     */
    public static String encrypt(String plainText, String key) throws Exception{
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, keySpec);
        byte[] encrypted = cipher.doFinal(plainText.getBytes(ENCODING));
        return Base64.encodeBase64String(encrypted);
    }

    /**
     * BASE64解密
     * @param cipherText
     * @param key
     * @return
     * @throws Exception
     */
    public static String decrypt(String cipherText, String key) throws Exception{
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(ENCODING), ALGORITHM);
        Cipher cipher = Cipher.getInstance(ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, keySpec);
        byte[] encryptedBytes = Base64.decodeBase64(cipherText);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, ENCODING);
    }

    public static String md5Encode(String str){
        StringBuffer newStr = new StringBuffer("");
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(str.getBytes());
            byte b[] = md.digest();
            int i;
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0){
                    i += 256;
                }
                if (i < 16){
                    newStr.append("0");
                }
                newStr.append(Integer.toHexString(i));
            }
            //32位加密
            return newStr.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return newStr.toString();
    }


}
